﻿using System;
using System.Windows;
using SimpleChat.ViewModel;
using GalaSoft.MvvmLight.Messaging;

namespace SimpleChat
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window 
    {
        public MainWindow()
        {
            InitializeComponent();
            Closing += (s, e) => ViewModelLocator.Cleanup();

            // Bind Messenger
            Messenger.Default.Register<DialogMessage>(this, HandleMessageBox);
            Messenger.Default.Register<WindowDialogMessage<Nullable<Boolean>>>(
                this, 
                (message) =>
                {
                    switch (message.WindowName)
                    {
                        case "JoinServer":
                            HandleOpenWindowJoinServer(message);
                            break;
                        case "CreateServer":
                            HandleOpenWindowCreateServer(message);
                            break;
                    }
                });

            // Bind Flash on new message
            ViewModelLocator.MainStatic.ChatMessages.CollectionChanged += (s, e) =>
            {
                if (!IsFocused)
                    FlashWindow.Flash(
                        new System.Windows.Interop.
                            WindowInteropHelper(this).
                            Handle);
            };
        }

        public void HandleMessageBox(DialogMessage message)
        {
            message.ProcessCallback(
                MessageBox.Show(
                    message.Content,
                    message.Caption,
                    message.Button,
                    message.Icon,
                    message.DefaultResult,
                    message.Options
                )
            );
        }

        public void HandleOpenWindowCreateServer(WindowDialogMessage<Nullable<Boolean>> message)
        {
            CreateServerWindow wdwCreateServer = new CreateServerWindow();
            message.ProcessCallback(wdwCreateServer.ShowDialog());
        }

        public void HandleOpenWindowJoinServer(WindowDialogMessage<Nullable<Boolean>> message)
        {
            JoinServerWindow wdwJoinServer = new JoinServerWindow();
            message.ProcessCallback(wdwJoinServer.ShowDialog());
        }
    }
}
